<?php

namespace App\Services;

use App\Caches\QrcodeJumpUrlCache;
use chillerlan\QRCode\Output\QROutputInterface;
use chillerlan\QRCode\QROptions;
use Endroid\QrCode\Color\Color;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelHigh;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\Writer\PngWriter;
use YQ\YqExtend;

class QrCodeService extends ServiceBase
{
    public function createQrcode(string $url)
    {
        $qr_code = new QrCode($url);
        $qr_code->setSize(250);// 内容区域宽高,默认为300
        $qr_code->setMargin(10);// 外边距大小,默认为10
        $qr_code->setEncoding(new Encoding('UTF-8'));// 设置编码
        $qr_code->setErrorCorrectionLevel(new ErrorCorrectionLevelHigh());// 设置容错等级
        $qr_code->setForegroundColor(new Color(0,0,0));// 设置二维码颜色,默认为黑色
        $qr_code->setBackgroundColor(new Color(255, 255, 255, 0));// 设置二维码背景色,默认为白色
        return $qr_code;
    }

    public function createQrcodeFile(string $url): string
    {
        $writer   = new PngWriter();
        $filename = $this->getCreateQrcodeDefaultFilename();
        $dir      = pathinfo($filename)['dirname'];
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }

        $qrcode = $this->CreateQrcode($url);
        $result = $writer->write($qrcode, null, null);
        $result->saveToFile($filename);

        return $filename;
    }

    public function getCreateQrcodeDefaultFilename(): string
    {
        return storage_path('/uploads/images/qrcode/' . date('Ym') . '/' . YqExtend::uniqid32() . '.png');
    }

    // 使用缓存保存要生成的二维码链接
    public function getJumpQrcodeUrl(string $url): string
    {
        $cache_id = YqExtend::uniqid32();
        $data = [
            'url' => $url,
        ];
        QrcodeJumpUrlCache::getInstance()->update($cache_id, $data);

        $jump_url = config('app.url') . "/qrcode_jump_url/index?cache_id={$cache_id}";

        return $jump_url;
    }

    // 用户扫码后先访问到我们地址
    // 再由我们地址进行跳转到真实的目的 url
    public function createQrcodeAndJumpUrl(string $url): string
    {
        $jump_url = $this->getJumpQrcodeUrl($url);
        return $this->createQrcodeFile($jump_url);
    }
}
